package com.welike.shibo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.welike.shibo.eneity.JsonResult;
import com.welike.shibo.eneity.SysRole;
import com.welike.shibo.enums.ResultEnum;
import com.welike.shibo.mapper.SysRoleMapper;
import com.welike.shibo.mapper.SysRolePermissionMapper;
import com.welike.shibo.service.SysRoleService;
import com.welike.shibo.utils.ResultUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * 角色Service实现类
 * @author fangyu
 * @date 2019/11/21
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService{

    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysRolePermissionMapper sysRolePermissionMapper;

    @Override
    public JsonResult getAllRoles() {
        List<JSONObject> roles = sysRoleMapper.getAllRoles();
        return ResultUtils.success("roles", roles);
    }

    @Override
    public JsonResult listRole() {
        List<JSONObject> roles = sysRoleMapper.listRole();
        return ResultUtils.success("roles", roles);
    }

    @Override
    public JsonResult listAllPermission() {
        List<JSONObject> permissions = sysRoleMapper.listAllPermission();
        return ResultUtils.success("permissions", permissions);
    }

    @Transactional(rollbackFor = Exception.class)
    @SuppressWarnings("unchecked")
    @Override
    public JsonResult addRole(JSONObject requestJson) {
        sysRoleMapper.insertRole(requestJson);
        sysRolePermissionMapper.insertRolePermission(requestJson.getString("roleId"), (List<Integer>) requestJson.get("permissions"));
        return ResultUtils.success("添加成功!");
    }

    @Transactional(rollbackFor = Exception.class)
    @SuppressWarnings("unchecked")
    @Override
    public JsonResult updateRole(JSONObject requestJson) {
        String roleId = requestJson.getString("roleId");
        List<Integer> newPermissions = (List<Integer>) requestJson.get("permissions");
        JSONObject roleInfo = sysRoleMapper.getRoleInfo(requestJson);
        Set<Integer> oldPermissions = (Set<Integer>) roleInfo.get("permissionIds");
        // 修改角色名称
        editRoleName(requestJson, roleInfo);
        // 添加新权限
        saveNewPermission(roleId, newPermissions, oldPermissions);
        // 移除旧的不再拥有的权限
        removeOldPermission(roleId, newPermissions, oldPermissions);
        return ResultUtils.success("更新成功!");
    }

    /**
     * 修改角色名称
     * @param paramJson 修改的信息
     * @param roleInfo 角色信息
     */
    private void editRoleName(JSONObject paramJson, JSONObject roleInfo){
        String roleName = paramJson.getString("roleName");
        if (!roleName.equals(roleInfo.getString("roleName"))){
            sysRoleMapper.updateRoleName(paramJson);
        }
    }

    /**
     * 为角色添加新权限
     * @param roleId 角色id
     * @param newPerms 新权限
     * @param oldPerms 旧权限
     */
    private void saveNewPermission(String roleId, Collection<Integer> newPerms, Collection<Integer> oldPerms){
        List<Integer> waitInsert = new ArrayList<>();
        for (Integer newPerm: newPerms){
            if (!oldPerms.contains(newPerm)){
                waitInsert.add(newPerm);
            }
        }
        if (waitInsert.size() > 0) {
            sysRolePermissionMapper.insertRolePermission(roleId, waitInsert);
        }
    }

    /**
     * 删除角色 旧的 不再拥有的权限
     * @param roleId 角色id
     * @param newPerms 新权限
     * @param oldPerms 旧权限
     */
    private void removeOldPermission(String roleId, Collection<Integer> newPerms, Collection<Integer> oldPerms) {
        List<Integer> waitRemove = new ArrayList<>();
        for (Integer oldPerm : oldPerms){
            if (!newPerms.contains(oldPerm)){
                waitRemove.add(oldPerm);
            }
        }
        if (waitRemove.size() > 0) {
            sysRolePermissionMapper.removeRolePermission(roleId, waitRemove);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @SuppressWarnings("unchecked")
    @Override
    public JsonResult deleteRole(JSONObject requestJson) {
        JSONObject roleInfo = sysRoleMapper.getRoleInfo(requestJson);
        List<JSONObject> users = (List<JSONObject>) roleInfo.get("users");
        if (users != null && users.size() > 0){
            return ResultUtils.error(ResultEnum.E_10008);
        }
        sysRoleMapper.removeRole(requestJson);
        sysRolePermissionMapper.removeRoleAllPermission(requestJson);
        return ResultUtils.success("删除成功!");
    }
}